import Web3 from "web3";
import { metaMaskMode } from "@/store/metamask";
import { log } from "../consoleLog";
import { Toast } from "vant";
// import i18n from '@/plugin/lang/i18n'
import getAbis from '@/contract/index'
import { ContractOptions } from "web3-eth-contract";



class result {
    state: boolean = true;
    msg: string = ''

}
var web3: Web3
var metaMaskStore: any
const metaMask = {

    //初始化
    //MetaMask injects a global API into websites visited by its users at window.ethereum. This API allows websites to request users' Ethereum accounts, read data from blockchains the user is connected to, and suggest that the user sign messages and transactions. The presence of the provider object indicates an Ethereum user. 
    init() {
        return new Promise((resolve, reject) => {
            //两种检测方案 检测小狐狸环境 和 window挂载的web3(文档没有)
            if (typeof (window as any).ethereum == 'undefined' || (typeof (window as any).web3 == 'undefined')) {
                reject(new Error('Consider installing MetaMask!'));
            } else {
                (window as any).ethereum.request({ method: 'eth_requestAccounts' }).then((res: any) => {
                    web3 = new Web3((window as any).ethereum)
                    metaMaskStore = metaMaskMode()
                    metaMaskStore.setWeb3(web3)
                    // 实例化 pinia
                    if (process.env.VUE_APP_OPEN_SIGN == 'true') {
                        log('签名认证', '开启')
                        web3.eth.personal.sign(web3.utils.fromUtf8(String(process.env.VUE_APP_SIGN_TIP)), res[0], '', (err: Error, res: string) => {
                            if (err) {
                                log('签名认证', '失败')
                                Toast((err as any).message)

                            } else {
                                log('签名认证', '成功')
                                this.setAccount(res[0])
                                // 当监听放在此处时,如果未签名,切换账号则无法监听
                                this.initEvent()
                            }
                        })
                    } else {
                        log('签名认证', '关闭')
                        this.setAccount(res[0])
                        this.initEvent()
                    }
                })

                this.getChainId().then(() => {

                    resolve(true)
                })


            }

        })
    },

    setAccount(account: string) {
        if (account) {
            metaMaskStore.setConnect(true)
            metaMaskStore.setAccount(account)
        }
    },
    // 获取当前链id
    getChainId() {
        return new Promise((resolve, reject) => {
            (window as any).ethereum.request({ method: 'eth_chainId' }).then((res: string) => {
                metaMaskStore.setChainId(web3.utils.hexToNumber(res))
                // 检测是否开启链限制展示
                if (process.env.VUE_APP_OPEN_CHECK_NETWORK == 'true') {
                    log('限制链环境', '开启')
                    let chainIdList: Array<number | string> = String(process.env.VUE_APP_OPEN_LIMIT_CHAIN_ID).split(',')
                    let isCurrentChain: boolean = false
                    chainIdList.forEach(item => {
                        if (web3.utils.hexToNumber(res) == item) {
                            isCurrentChain = true
                        }

                    })
                    if (isCurrentChain) {
                        log('符合条件环境', '是')
                        resolve(true)
                    } else {
                        log('符合条件环境', '否')
                        reject(false)

                        Toast({
                            type: 'fail',
                            message: '链环境不正确',
                            duration: 0,
                            forbidClick: true,
                        })
                    }

                } else {
                    log('限制链环境', '关闭')
                    resolve(true)

                }
            })
        })
    },
    //监听事件
    initEvent() {
        (window as any).ethereum.on('accountsChanged', (accounts: Array<string>) => {
            this.setAccount(accounts[0])
            window.location.reload();
        }),
            (window as any).ethereum.on('chainChanged', (chainId: any) => {

                window.location.reload();
            });

    },

    getContract(web3: Web3, abis: any) {
        if (web3 && abis) {
            // 判断初始化gas 
            let sendData: ContractOptions
            if (Number(process.env.VUE_APP_GAS_LIMIT) > 0) {
                log('初始化gas', String(process.env.VUE_APP_GAS_LIMIT))
                sendData = {
                    from: metaMaskStore.getAccount(),
                    gas: Number(process.env.VUE_APP_GAS_LIMIT),
                }
            } else {
                log('自动推算gas', '开启')
                console.warn('自动推算gas开启时,适合于eth链货币交易,易出问题')
                web3.eth.getGasPrice().then(res => {
                    log('当前gas', String(Number(res) * 1.1))

                    sendData = {
                        from: metaMaskStore.getAccount(),
                        gas: Number(res) * 1.1,
                    }
                })
            }
            Object.keys(abis).forEach(key => {
                let contract = new web3.eth.Contract(abis[key].default.ABI, process.env.NODE_ENV == 'production' ? abis[key].default.ADDRESS_PROD : abis[key].default.ADDRESS_DEV, sendData)
                metaMaskStore.contract[key] = contract
                log(key, '完成')
            })
            log('合约自动化', '完成')
        }
    },


}

export default metaMask


